package plgbase

import (
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/gobase"
	"gitee.com/ymofen/gobase/factory"
	"gitee.com/ymofen/gobase/subpub"
	"gitee.com/ymofen/supervalue"
	"io"
	"sync/atomic"
)

type BaseSubNode struct {
	subSessionPrefix string
	subsessionid     string
	subconnstr       string
	stepMsg          string
	errmsg           string

	conf      gobase.StrMap
	objectRef *gobase.ObjectInnerRef
	sub       subpub.ISubA
	subTopics map[string]struct{}
}

var (
	subnodesessionN int32
)

// subprefix 创建session时的前缀
func NewBaseSubNode(subprefix string) *BaseSubNode {
	rval := &BaseSubNode{subSessionPrefix: subprefix}
	return rval
}

func (this *BaseSubNode) GetSubSessionID() string {
	return this.subsessionid
}

func (this *BaseSubNode) ConfString() string {
	return this.subconnstr
}

func (this *BaseSubNode) StatusText() string {
	return fmt.Sprintf("%s, step:%s", this.ConfString(), this.stepMsg)
}

func (this *BaseSubNode) closeSub() {
	if this.objectRef != nil {
		this.stepMsg = fmt.Sprintf("[%s]closeSub->DelSession:0", utils.NowString())
		sub := this.sub
		if sub != nil && len(this.subTopics) > 0 {
			for k, _ := range this.subTopics {
				sub.Unsub(this.subsessionid, k)
			}
			this.subTopics = nil
		}

		this.objectRef.ReleaseRef()
		this.stepMsg = fmt.Sprintf("[%s]closeSub->DelSession:1", utils.NowString())
		this.subsessionid = ""
		this.subconnstr = ""
	}
}

func (this *BaseSubNode) Close() error {
	if len(this.subsessionid) == 0 {
		return io.ErrClosedPipe
	}
	this.closeSub()
	return nil
}

func (this *BaseSubNode) GetStepMsg() string {
	return this.stepMsg
}

func (this *BaseSubNode) ReloadConnConfString(str string, notify subpub.SubFunc) error {
	if str != this.subconnstr {
		confMap := gobase.NewStrMap()
		this.closeSub()
		this.subconnstr = str
		confMap.URLFormDecode(str)

		return this.checkSub(confMap, notify)
	}
	return nil
}

func (this *BaseSubNode) checkGetObj(conf gobase.StrMap) (*gobase.ObjectInnerRef, error) {
	conntype := conf.StringByName("conntype", "")
	conntype = fmt.Sprintf("subnode.%s", conntype)
	obj, err := factory.CreateInstance(conntype, conf)
	if err != nil {
		return nil, err
	}

	if lvintf, ok := obj.(*gobase.ObjectInnerRef); ok {
		return lvintf, nil
	} else {
		return nil, fmt.Errorf("%s不是gobase.ObjectInnerRef对象", conntype)
	}
}

func (this *BaseSubNode) checkSub(confMap gobase.StrMap, notify subpub.SubFunc) error {
	if len(this.subsessionid) == 0 {
		this.subsessionid = fmt.Sprintf("%s-sub-%d", this.subSessionPrefix, atomic.AddInt32(&subnodesessionN, 1))
	}
	this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:0", utils.NowString())
	objref, err := this.checkGetObj(confMap)
	if err != nil {
		this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:-1, err:%s", utils.NowString(), err.Error())
		return err
	} else {
		this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:1", utils.NowString())
		this.objectRef = objref
		this.sub = objref.GetObject().(subpub.ISubA)
		subtopics := make(map[string]struct{})

		this.sub.Sub(this.subsessionid, "evt-sub", notify)
		subtopics["evt-sub"] = struct{}{}

		this.sub.Sub(this.subsessionid, "evt", notify)
		subtopics["evt"] = struct{}{}

		topic := confMap.StringByName("topic", "")
		if len(topic) == 0 {
			topic = "sub" // 订阅默认的接收通道
		}
		this.sub.Sub(this.subsessionid, topic, notify)
		subtopics[topic] = struct{}{}
		this.subTopics = subtopics

		err = this.objectRef.CheckStart()
		if err == gobase.ErrUnsupported {
			this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:2, checkstart unsupoort!", utils.NowString())
		} else {
			this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:2", utils.NowString())
		}

		return err
	}
}

func (this *BaseSubNode) ReloadConf(conf *wrapper.SuperValue, onsub subpub.SubFunc) error {
	if conf == nil {
		this.closeSub()
		return nil
	}

	confMap := gobase.NewStrMap()
	str := conf.String()
	if str != this.subconnstr {
		this.closeSub()
		this.subconnstr = str
		if conf.IsString() {
			confMap.URLFormDecode(str)
		} else if conf.IsObject() {
			url := conf.StringByName("url", "")
			if len(url) > 0 {
				confMap.URLFormDecode(url)
			}
			conf.Range(func(key string, val *wrapper.SuperValue) bool {
				confMap[key] = val.String()
				return true
			})
		}

		return this.checkSub(confMap, onsub)

	}
	return nil
}
